﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace SlamCms.SharePoint.Tagging
{
	public static class TreeViewExtender
	{
		public static TreeNode FindChildNode(this TreeView tree, string value)
		{
			TreeNode returnNode = null;
			foreach (TreeNode node in tree.Nodes.Cast<TreeNode>().Reverse())
			{
				returnNode = FindChildNodeInternal(node, value);
				if (returnNode != null)
				{
					break;
				}
			}
			return returnNode;
		}

		private static TreeNode FindChildNodeInternal(TreeNode node, string value)
		{
			TreeNode returnNode = null;
			if (node.Value == value)
			{
				returnNode = node;
			}
			else
			{
				foreach (TreeNode childNode in node.ChildNodes.Cast<TreeNode>().Reverse())
				{
					returnNode = FindChildNodeInternal(childNode, value);
					if (returnNode != null)
					{
						break;
					}
				}
			}
			return returnNode;
		}
	}
}
